import Vue from 'vue'
import VueRouter from 'vue-router'
// 路由懒加载
import store from '../store' // vuex动态挂载路由
import routes from './routes' // 导入登录页入口

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL, // 默认路由配置模式 在config里面配置
  routes
})

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  if (store.state.isToken) {
    /* const { userInfo, authList } = store.state
    if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
      store.dispatch('GetUserInfo').then(res => { // 拉取user_info
        const roles = res.data.roles // note: roles must be a array! such as: ['editor','develop']
        store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表
          router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
        })
      }).catch((err) => {
        store.dispatch('FedLogOut').then(() => {
          next({ path: '/' })
        })
      })
    } */
    router.addRoute(store.state.routerList)
    next({ ...to, replace: true })
  } else {
    next({ path: '/login' })
  }
})
// 路由后置守卫
router.afterEach((to, from) => {})

export default router
